<?php

namespace App\Admin\Controller;

class Login extends \Controller {
    
    public function index() {
        
        // 首次登陆必须设置超级管理员密码
        
        if (!QF()->Admin()->get(1, 'password')) {
            fail('首次登陆请设置超级管理员密码', $this->createUrl('login', 'reset'));
        }
        
        if ($this->request->isPost()) {
            if (\Auth::isAuthed(MODULE_NAME)) {
                $this->gotoUrl('index');
            }
            
            $username = $this->request->getPost('username', '');
            $password = $this->request->getPost('password', '');
            $valicode = $this->request->getPost('valicode', '');
            
            if (!\Image::chkVerify($valicode)) {
                fail('验证码不正确');
            } elseif (trim($password) == '') {
                fail('密码不能为空');
            } elseif (trim($username) == '') {
                fail('用户名不能为空');
            }
            
            $uid = QF()->Admin()->checkLogin($username, $password);
            if ($uid) {
                \Auth::Login($uid, MODULE_NAME);
                $this->gotoUrl('index');
            } else {
                fail('用户名或密码不正确');
            }
        }
    }
    
    public function logout() {
        \Auth::Logout();
        die('<script type="text/javascript">top.location.href="/admin"</script>');
    }
    
    public function reset() {
        
        // 已设置过密码，不可以设置密码了
        if (QF()->Admin()->get(1, 'password')) {
            fail('非法访问');
        }
        
        if ($this->request->isPost()) {
            $password = trim($this->request->getPost('password'));
            
            if (!$password) {
                fail('请输入密码');
            }
            
            $result = QF()->Admin()->updatePasswordForce(1, $password);
            
            if ($result) {
                succ('', $this->createUrl('login'));
            } else {
                fail();
            }
        }
        
    }
    
}
